package com.mantru.iotpot.Util

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.widget.ProgressBar
import android.widget.Toast
import androidx.core.content.FileProvider
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL

class DownloadUtil {

    private var isCancelled = false

    // 定义进度回调接口
    interface DownloadProgressCallback {
        fun onProgressUpdate(progress: Int)
        fun onDownloadComplete(filePath: String)
        fun onError(e: Exception)
    }

    // 下载 APK
    fun downloadApk(
        context: Context,
        url: String,
        callback: DownloadProgressCallback
    ) {
        Thread {
            var connection: HttpURLConnection? = null
            var inputStream: InputStream? = null
            var outputStream: FileOutputStream? = null
            var file: File? = null

            try {
                var currentUrl = url
                var redirectCount = 0

                // 处理重定向
                do {
                    connection = URL(currentUrl).openConnection() as HttpURLConnection
                    connection.instanceFollowRedirects = false
                    connection.connect()

                    when (connection.responseCode) {
                        in 300..399 -> {
                            currentUrl = connection.getHeaderField("Location")
                                ?: throw IOException("Redirect location missing")
                            redirectCount++
                            if (redirectCount > 5) throw IOException("Too many redirects")
                            connection.disconnect()
                        }
                        !in 200..299 -> throw IOException("HTTP ${connection.responseCode}")
                        else -> break
                    }
                } while (true)

                val fileSize = connection!!.contentLength
                inputStream = connection.inputStream
                file = File(context.getExternalFilesDir(null), "app.apk").apply {
                    if (exists()) delete()
                }
                outputStream = FileOutputStream(file)

                val buffer = ByteArray(1024)
                var downloadedSize = 0
                var len: Int

                while (inputStream.read(buffer).also { len = it } != -1) {
                    if (isCancelled) break
                    downloadedSize += len
                    outputStream.write(buffer, 0, len)
                    outputStream.flush() // 强制写入
                    if (fileSize > 0) {
                        val progress = (downloadedSize * 100 / fileSize).toInt()
                        callback.onProgressUpdate(progress)
                    }
                }

                if (isCancelled) {
                    file.delete()
                    return@Thread
                }

                // 校验文件完整性
                if (fileSize > 0 && file.length() != fileSize.toLong()) {
                    throw IOException("File corrupted: size mismatch")
                }

                callback.onDownloadComplete(file.absolutePath)
            } catch (e: Exception) {
                file?.delete()
                callback.onError(e)
            } finally {
                outputStream?.close()
                inputStream?.close()
                connection?.disconnect()
            }
        }.start()
    }

    // 添加取消方法
    fun cancel() {
        isCancelled = true
    }

    // 安装 APK
    fun installApk(context: Context, apkPath: String) {
        val file = File(apkPath)
        val uri = FileProvider.getUriForFile(
            context,
            "${context.packageName}.fileprovider",
            file
        )

        val intent = Intent(Intent.ACTION_VIEW).apply {
            data = uri
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        }

        // 确保有 Activity 能处理此 Intent
        if (intent.resolveActivity(context.packageManager) != null) {
            context.startActivity(intent)
        } else {

        }
    }
}